<template>
    <div style="padding: 10px;">
        <van-uploader
                :max-count="1"
                v-model="allInfoList"
                :multiple="false"
                :disabled="false"
                :after-read="afterRead"
                :before-read="beforeRead"
                @oversize="onOversize"
                :preview-image="true"
        />
  </div>
</template>


<script lang="ts">
import {defineComponent, ref, watch, onMounted, computed} from "vue";
import {closeToast, showConfirmDialog, showLoadingToast, showToast} from "vant";
import XEUtils from "xe-utils";
import {useUpload} from "@/config/upload";
// import {upload, getFileList, previewImgUrl, delUpload, previewVideoUrl} from "@/api/file";
// import {ImagePreview} from "vant";

export default defineComponent({
    name: "VantUpload",
    components: {},
    props: {
        modelValue: {
            //受控图片列表
            type: Array,
            default: () => [],
        },
        accept: {
            type: String,
            default: () => ".jpg,.png,.jpeg,.mp4,.MOV,.mp3,.m4a",
        },
        maxCount: {
            type: Number,
            default: 9,
        },
        uploadAction: {
            type: String,
            default: `${import.meta.env.VITE_API_BASE_API}${
                import.meta.env.VITE_API_URL
            }api/file/uploadFile`,
        },
        disabled: {
            type: Boolean,
            default: false,
        },
        maxSize: {
            type: Number,
            default: () => {
                return 20;
            },
        },
        // 上传区域大小
        previewSize: {
            type: String,
            default: () => {
                return "100";
            },
        },
        isReqUpload: {
            type: Boolean,
            default: false,
        },
    },
    emits: ['update:modelValue'],
    setup(props, _) {
        const {uploadUrl, httpRequest} = useUpload()
        const show = ref(false);
        const allInfoList = ref<any[]>([]);
        const imgList = ref([]);
        const url = ref("");
        const urlType = ref("");
        const videoUrl:any = ref("");
        const maxFileSize = computed(() => {
            return props.maxSize * 1024 * 1024
        })

        // const getFile = () => {
        //     getFileList(props.billId).then((res: any) => {
        //         if (res.code === 200) {
        //             res.data.forEach((k, index) => {
        //                 k.url = previewImgUrl(k.id)
        //             });
        //             updateFileStatus(res.data, "done", "上传成功");
        //             allInfoList.value = res.data
        //             _.emit("update:modelValue", allInfoList.value);
        //         }
        //     })
        // }
        // watch(() => props.billId, (val) => {
        //     if (val) {
        //         getFile()
        //     }
        // }, {
        //     immediate: true,
        //     deep: true,
        // })


        // 上传前拦截
        function beforeRead(file) {
            file = XEUtils.isArray(file) ? file : [file];
            let arr = props.accept.split(",");
            let flag = file.every((j: any) => {
                return arr.includes(subFileName(j.name));
            });
            if (!flag) {
                showToast(`只支持${props.accept}格式上传`);
                return false;
            }
            if (Number(allInfoList.value.length + file.length) > props.maxCount) {
                showToast(`选择图片超过限制，最大上传数为${props.maxCount}`);
                return false;
            }
            return true;
        }

        const onOversize = (file) => {
            showToast(`所选文件超过限制大小，${props.maxSize}MB`);
        };

        function subFileName(name) {
            return name.substring(name.lastIndexOf(".")); //截取后缀   输出：.png
        }

        // 上传方法
        async function afterRead(file) {
            if (props.isReqUpload) {
                file = XEUtils.isArray(file) ? file : [file];
                try {
                    // updateFileStatus(file, "uploading", "上传中...");
                    showLoadingToast({
                        duration: 0,
                        forbidClick: true,
                        message: '上传中...',
                    });
                    let pormise = file.map((j: any) => {
                        return httpRequest(j);
                    });
                    let resMap = await Promise.all(pormise);
                    closeToast();
                    showToast(`上传成功`);
                    // updateFileStatus(file, "done", "上传成功");
                    console.log(allInfoList.value,'beforeReadbeforeReadbeforeRead')
                    _.emit("update:modelValue", resMap.map(j => j.data));
                } catch (e) {
                    // updateFileStatus(file, "failed", "上传失败");
                    deleteErrFile();
                    closeToast();
                    showToast(`上传失败`);
                }
            } else {
                _.emit("update:modelValue", [file]);
            }
        }

        // 修改文件状态
        function updateFileStatus(file, status = "", message = "") {
            file.forEach((j) => {
                j.status = status;
                j.message = message;
            });
        }

        //根据文件名来查找到文件列表中要删除的文件
        function deleteErrFile() {
            allInfoList.value.forEach((item, index) => {
                if (item.status === "failed") {
                    allInfoList.value.splice(index, 1);
                }
            });
        }

        //手动点击删除，修改包含所有信息的文件列表，通过watch根据该列表动态修改图片文件列表
        function afterDelete(file) {
            let name = file.name;
            allInfoList.value.forEach((item, index) => {
                if (item.originalName === name) {
                    allInfoList.value.splice(index, 1);
                }
            });
            return true;
        }

        //取消掉组件自带的点击预览功能，自己添加（系统自带预览点击视频时会先视频的播放图片）
        function handleclicksc(file) {
            if (file.docType === "mp4" || file.docType === "MOV") {
                url.value = file.url;
                urlType.value = "video";
                show.value = true;
            }
            if (
                file.docType === "png" ||
                file.docType === "jpg" ||
                file.docType === "jpeg"
            ) {
                // ImagePreview({
                //     images: [
                //         file.url
                //     ],
                //     startPosition: 0,
                //     closeable: true,
                // });
            }
        }
        //
        //
        // watch(
        //     () => props.modelValue,
        //     (newVal) => {
        //         allInfoList.value = newVal;
        //     },
        //     {deep: true}
        // );

        // 附件预览
        function handlerPreview(file) {
            // let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
            // let urlPath:any = previewImgUrl(file.id)
            // if (isAssetTypeAnImage(fileType)) {
            //     urlPath = previewImgUrl(file.id)
            //     ImagePreview({
            //         images: [urlPath],
            //         startPosition: 0,
            //         closeable: true,
            //     });
            // } else if (isAssetTypeAnVideo(fileType)) {
            //     urlPath = previewVideoUrl(file.id)
            //     videoUrl.value = urlPath;
            //     urlType.value = "video";
            //     show.value = true;
            // } else {
            //     let fileUrl
            //     if (file.name.endsWith('.mp3') || file.name.endsWith('.m4a')) {
            //         fileUrl = previewVideoUrl(file.id)
            //     } else {
            //         fileUrl = previewImgUrl(file.id)
            //     }
            //     let oInput = document.createElement("input"); // 创建input标签存放地址
            //     oInput.value = fileUrl; // 给input标签赋值
            //     document.body.appendChild(oInput); // 将input标签添加到body里
            //     oInput.select(); // 选择对象
            //     document.execCommand("Copy"); // 执行浏览器复制命令
            //     oInput.className = "oInput";
            //     oInput.style.display = "none"; // 隐藏input
            //     showToast('链接已复制，请在浏览器中打开')
            // }
        }
        // 附件预览
        function isFileType(file) {
            if (!file)  {
                return ''
            }
            let fileType = file.substring(file.lastIndexOf(".") + 1);
            if (isAssetTypeAnImage(fileType)) {
                return 'img'
            }
            if (isAssetTypeAnVideo(fileType)) {
                return 'video'
            }
        }

        function isAssetTypeAnImage(ext) {
            if (!ext) return false
            return [
                'png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(ext.toLowerCase()) !== -1;
        }

        function isAssetTypeAnVideo(ext) {
            if (!ext) return false
            return [
                'mp4', 'mov'].indexOf(ext.toLowerCase()) !== -1;
        }

        // 附件删除
        const deleteFile = async (item) => {
            showConfirmDialog({
                title: '提示',
                message:
                    '是否确认删除?',
            })
                .then(async () => {
                })
                .catch(() => {
                    // on cancel
                });
        }
        onMounted(() => {
            allInfoList.value = props.modelValue;
        });

        return {
            allInfoList,
            url,
            show,
            urlType,
            imgList,
            beforeRead,
            afterRead,
            onOversize,
            maxFileSize,
            handlerPreview,
            deleteFile,
            isFileType,
            videoUrl,
        };
    },
});

</script>

<style scoped lang="scss">
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.img-block {
  position: relative;

  img {
    z-index: 99;
    max-width: 100%;
    height: auto;
    object-fit: cover;
  }

  video {
    width: 100%;
    max-height: 100vh;
  }
}

.video-delete {
  width: 45px;
  position: absolute;
  top: 60px;
  left: calc(100vw - 60px);
  font-size: 32px;
  color: #ffffff;
}

.file-warp{
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
}
.file-item {
  margin-top: 10px;
  margin-right: 10px;
  position: relative;

  .file-item-image {
    width: 75px;
    height: 75px;
  }

  .file-item-right {
    background: red;
    width: 15px;
    height: 15px;
    display: flex;
    align-items: center;
    position: absolute;
    right: 0;
    top: 0;
  }
.video-play{
    color: #ffffff;
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    position: absolute;
    left: 10px;
    top: 7px;
    font-size: 56px;
}
}
</style>
